package com.zx;


import com.zx.dao.Configuration;
import com.zx.dao.MappedStatement;
import com.zx.enums.SqlCommandType;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.util.List;

/**
 * @ProjectName: myjdbc
 * @Package: com.zx
 * @ClassName: XMLMapperBuilder
 * @Author: 1
 * @Description: 1
 * @Date: 2021/9/6 19:13
 */
public class XMLMapperBuilder {

    private Configuration configuration;

    public XMLMapperBuilder(Configuration configuration) {
        this.configuration =configuration;
    }

    public void parse(InputStream inputStream) throws DocumentException {
        Document document = new SAXReader().read(inputStream);
        Element rootElement = document.getRootElement();
        String namespace = rootElement.attributeValue("namespace");
        parameterMapElement(namespace, rootElement.selectNodes("//select"),SqlCommandType.SELECT);
        parameterMapElement(namespace, rootElement.selectNodes("//delete"),SqlCommandType.DELETE);
        parameterMapElement(namespace, rootElement.selectNodes("//update"),SqlCommandType.UPDATE);
        parameterMapElement(namespace, rootElement.selectNodes("//insert"),SqlCommandType.INSERT);

    }

    /**
     * 解析xml
     * @param namespace: 空间名
     * @param list:
     * @param sqlCommandType:
     */
    private void parameterMapElement(String namespace,List<Element> list,SqlCommandType sqlCommandType){
        for (Element element : list) {
            String id = element.attributeValue("id");
            String resultType = element.attributeValue("resultType");
            String parameterType = element.attributeValue("paramterType");
            String sqlText = element.getTextTrim();
            MappedStatement mappedStatement = new MappedStatement(sqlCommandType);
            mappedStatement.setId(id);
            mappedStatement.setResultType(resultType);
            mappedStatement.setParameterType(parameterType);
            mappedStatement.setSql(sqlText);
            String key = namespace+"."+id;
            configuration.getMappedStatementMap().put(key,mappedStatement);
        }
    }
}
